'use strict';
module.exports = {
	/**
	 * XXXnameXXX
	 * @url client/user/pub/Paycallback 前端调用的url参数地址
	 * data 请求参数
	 * @param {String} params1  参数1
	 */
	main: async (event) => {
		let {
			data = {}, userInfo, util, filterResponse, originalParam
		} = event;
		let {
			customUtil,
			uniID,
			config,
			pubFun,
			vk,
			db,
			_
		} = util;
		let {
			uid,
			total_fee,
			out_trade_no,
			_add_time,
			_add_time_str
		} = data;
		let res = {
			code: 0,
			msg: ""
		};
		// 业务逻辑开始-----------------------------------------------------------
		// 业务逻辑开始-----------------------------------------------------------

		res.tips = ""

		// 把requestId和订单号存到-vktest表，出问题时方便追踪
		let requestid_log = await db.collection('vk-test').add({
			tips: "执行了扣量回传函数",
			request_id: event.originalParam.context.requestId,
			out_trade_no: out_trade_no
		});
		console.log("获取用户支付金额0", total_fee);

		// 使用vk公共函数需现在页面顶部引入VK框架，获取今日0点时间戳
		let {
			todayStart
		} = vk.pubfn.getCommonTime(new Date());

		// 获取充值订单信息
		let temp_info = await db.collection('a_recharge').where({
			out_trade_no: out_trade_no
		}).get();
		let orderinfo = temp_info.data[0];
		console.log("订单信息====", orderinfo);
		let clickid = temp_info.data[0].clickid || "";

		if (!clickid || clickid === "NoClickid" || clickid.length < 17) {
			res.tips = "不存在clickid";
			await failcallback(res.tips);
			return res;
		}

		// 获取回传比例配置
		let percent = await getBackhaulPercent(orderinfo, db);
		console.log("获取回传配置", percent);

		// 获取计划信息
		let planInfo = await getPlanInfo(orderinfo, db);

		// 根据配置决定是否回传
		await decideAndPerformBackhaul(planInfo, percent, orderinfo, db, clickid, total_fee, todayStart);

		async function getBackhaulPercent(orderInfo, db) {
			let percent = await db.collection('a_config').where({
				name: "RebackPercent",
				tfid: orderInfo.tfid
			}).get();

			if (percent.data.length === 0) {
				percent = await db.collection('a_config').where({
					name: "RebackPercent",
					user_id: orderInfo.invite_code || 0
				}).get();
			}

			if (percent.data[0]) {
				console.log("存在代理商比例数据", percent);
			} else {
				console.log("不存在代理商比例数据");
			}

			return percent.data[0];
		}

		async function getPlanInfo(orderinfo, db) {
			console.log("获取用户信息", orderinfo);
			let defaultPlanInfo = {
				proportion_value: 1,
				planId: orderinfo.promotion_id,
				advertiser_id: orderinfo.advertiser_id,
				userId: orderinfo.user_id,
			};

			const planInfoQuery = await db.collection('PlanCallback').where({
				planId: orderinfo.promotion_id
			}).get();

			if (planInfoQuery.data.length === 0) {
				// 如果没有找到对应的计划信息，则使用默认值并保存到数据库
				await db.collection('PlanCallback').add(defaultPlanInfo);
				return defaultPlanInfo;
			} else {
				// 如果找到了对应的计划信息，则更新比例值并返回查询结果
				await db.collection('PlanCallback').where({
					planId: orderinfo.promotion_id
				}).update({
					proportion_value: _.inc(1),
					advertiser_id: orderinfo.advertiser_id,
					userId: orderinfo.user_id,
				});
				return planInfoQuery.data[0];
			}
		}

		async function decideAndPerformBackhaul(planInfo, percent, orderInfo, db, clickid, total_fee,
			todayStart) {
			console.log("获取金额3", total_fee);

			// 冷启动回传逻辑独立于firstorder和newuser条件
			const firstOrderCheckmm = await isFirstOrder(orderInfo, db);

			if (firstOrderCheckmm) {


				if (planInfo.proportion_value <= percent.lqdhcbs && orderinfo.promotion_id) {
					await performBackhaul(planInfo, orderInfo, clickid, total_fee, db, "冷启动回传");
					return
				}

				if (planInfo.proportion_value > percent.lqdhcbs && orderinfo.promotion_id) {
					const newsday = shouldBackhaulNewUsers(orderInfo, percent, todayStart);

					if (orderInfo.user_register_date >= newsday) {
						// let firstorder =   percent.firstorder // 是否为用户的首笔订单 
						// 根据firstorder和newuser条件决定是否回传
						// if (firstorder) {
						// 检查是否为用户的首笔订单
						// const firstOrderCheck = await isFirstOrder(orderInfo, db);

						// if (firstOrderCheck) {
						await handleBackhaulBasedOnAmounts(planInfo, percent, orderInfo, clickid,
							total_fee, db,
							"首笔订单回传");
						// }
						//  else {
						// 	console.log("不是首笔订单");
						// 	return
						// }
						// } 

						// else {
						// 	// 不是首笔订单条件，直接回传
						// 	console.log("非首笔订单回传", total_fee);
						// 	await handleBackhaulBasedOnAmounts(planInfo, percent, orderInfo, clickid, db,
						// 		total_fee
						// 	);
						// }
					} else {
						console.log("用户注册日期不符合条件，不执行回传");
						res.tips = "用户注册日期不符合条件，不执行回传"
						await failcallback(res.tips);
						return
					}

				}




			} else {
				console.log("该用户不是首笔订单 结束 不回传");
				res.tips = "该笔订单不是首笔订单 结束 不回传";
				await failcallback(res.tips);
				return
			}




		}
		async function isFirstOrder(orderInfo, db) {
			// 检查是否为用户的首笔订单
			const userRechargeNum = await db.collection('a_recharge').where({
				pay_status: 1,
				user_id: orderInfo.user_id,
				tfid: orderInfo.tfid
			}).count();

			return userRechargeNum.total === 1;
		}

		function shouldBackhaulNewUsers(orderInfo, percent, todayStart) {
			let newuser = percent.newuser // 是否为新用户或最近hour_backhaul小时内的用户

			if (newuser === 0) {
				newuser = false

			} else {
				newuser = true
			}
			const hour_backhaul = percent.hour_backhaul || 24;

			if (newuser) {
				console.log("仅回传今日新用户的充值订单,此处不return,继续执行下面逻辑");
				return todayStart;
			} else {
				todayStart = 0;
				console.log("已把todayStart改为0");
				return new Date().getTime() - 3600000 * hour_backhaul;
			}
		}


		async function performBackhaul(orderInfo, clickid, total_fee, db, reason) {
			await douyin(clickid, total_fee, db);
			await logBackhaul(reason, orderInfo, db);
		}

		async function handleBackhaulBasedOnAmounts(planInfo, percent, orderInfo, clickid, db, total_feemoney) {
			const moneyQujian = percent.amountRanges || [];
			console.log("moneyQujian", moneyQujian);
			console.log("获取用户支付金额", total_feemoney);
			for (const item of moneyQujian) {
				if (item.radio === 1 && item.startAmount * 100 < total_fee && total_fee <= item.endAmount *
					100) {
					console.log("进入了全量回传");
					await performBackhaul(orderInfo, clickid, total_fee, db, "区间全量回传");
					break;
				} else if (item.radio === 2) {
					res.tips = "在全量不回传区间";
					await logBackhaul("区间全量不回传", orderInfo, db);
				} else if (item.radio === 3 && item.startAmount * 100 < total_fee && total_fee <= item
					.endAmount * 100) {

					console.log("以进入自定义回传比例");

					const orderNum = await updateProportionValue(orderInfo.tfid, total_feemoney);
					const ratioSum = Number(item.startnum) + Number(item.endnum); //比例之和
					const returnRatio = Number(item.endnum); // 回传比例
					console.log("orderNum", orderNum);
					console.log("ratioSum", ratioSum);
					console.log("returnRatio", returnRatio);
					if (orderNum == 0) {
						res.tips = "比例数值计算错误";
						await failcallback(res.tips);
						return res

					}

					if ((orderNum % ratioSum) <= returnRatio && (orderNum % ratioSum) > 0) {
						await performBackhaul(orderInfo, clickid, total_fee, db, "循环回传");
						console.log("循环回传");
					} else {
						console.log("循环回传但不回传不满足比例");
						res.tips = "循环回传但不回传不满足比例";
						await failcallback(res.tips);
						await logBackhaul("循环回传但不回传不满足比例", orderInfo, db);
					}
				}
			}
		}


		async function failcallback(tips) {
			await vk.baseDao.update({
				dbName: "a_recharge", // 表名
				whereJson: { // 条件
					out_trade_no: out_trade_no
				},
				dataJson: { // 需要修改的数据
					tips: tips //订单是否回传
				}
			});

		}

		async function updateProportionValue(tfid, total_fee) {
			try {
				// 获取文档
				let percentaa = await db.collection('a_config').where({
					name: "RebackPercent",
					tfid: tfid
				}).get();

				let mm = percentaa.data[0].amountRanges;

				let matchingIndex = -1;
				console.log("111", total_fee);
				console.log("2222", mm);

				// 使用 findIndex 方法查找符合条件的元素的索引
				matchingIndex = mm.findIndex(item => {
					return item.startAmount * 100 < total_fee && total_fee <= item.endAmount * 100;
				});

				console.log("33333", matchingIndex);

				if (matchingIndex !== -1) {
					// 使用模板字符串来进行字符串拼接
					let arrayIndex = `amountRanges.${matchingIndex}.proportion_value`;
					await db.collection('a_config').where({
						name: "RebackPercent",
						tfid: tfid
					}).update({
						[arrayIndex]: _.inc(1)
					});

				}

				// 重新获取文档以获取更新后的 proportion_value
				let updatedPercentaa = await db.collection('a_config').where({
					name: "RebackPercent",
					tfid: tfid
				}).get();

				let updatedMm = updatedPercentaa.data[0].amountRanges;

				for (const item of updatedMm) {
					if (item.startAmount * 100 < total_fee && total_fee <= item.endAmount * 100) {
						// 返回更新后的 proportion_value
						return item.proportion_value;
					}
				}



				// 如果没有找到匹配的区间，返回默认值
				return 0;
			} catch (error) {
				console.error('Error in updateProportionValue:', error);
				throw error;
			}
		}
		async function douyin(clickid, total_fee, db) {
			const jlurl =
				`https://ad.toutiao.com/track/activate/?callback=${clickid}&event_type=2&props=%7b%22pay_amount%22%3a${total_fee}%7d`;
			const tthuichuan_result = await uniCloud.httpclient.request(jlurl, {
				method: 'GET',
				data: {},
				contentType: 'json',
				dataType: 'json'
			});

			if (tthuichuan_result.data.code === 0 || tthuichuan_result.data.status === 200) {
				console.log("回传成功");
				await vk.baseDao.update({
					dbName: "a_recharge",
					whereJson: {
						out_trade_no: out_trade_no
					},
					dataJson: {
						is_backhaul: true,
					}
				});
			}

			// 回传记录入库
			await logBackhaul("douyin", orderinfo, db, tthuichuan_result.data);
		}

		async function logBackhaul(reason, orderInfo, db, result) {
			await db.collection('vk-test').add({
				tips: reason,
				tiptext: "callback",
				out_trade_no: out_trade_no,
				request_id: event.originalParam.context.requestId,
				total_fee: total_fee,
				_add_time: _add_time,
				_add_time_str: _add_time_str
			});

			await db.collection('jl_huichuanjilu').add({
				type: "active_pay",
				platform: "douyin",
				user_id: orderInfo.user_id,
				tfid: orderInfo.tfid || "",
				agent_id: orderInfo.invite_code || 0,
				middleman_id: orderInfo.middleman_id || 0,
				adid: orderInfo.ad_id,
				clickid: orderInfo.clickid,
				money: total_fee,
				result: result,
				out_trade_no: out_trade_no,
				time: _add_time,
				time_str: _add_time_str
			});
		}



		// 业务逻辑结束-----------------------------------------------------------
		return res;
	}
}